package com.hulman.oms.web;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.hulman.oms.bean.Result;
import com.hulman.oms.bean.Material;
import com.hulman.oms.bean.Tool;
import com.hulman.oms.service.MaterialService;
import com.hulman.oms.util.NumberUtil;
import com.hulman.oms.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: maxwellens
 */
@RestController
public class MaterialController
{
    @Autowired
    private MaterialService materialService;

    @Autowired
    private HttpServletResponse response;

    @GetMapping("/materials/{id}")
    public Result findMaterialById(@PathVariable Integer id)
    {
        Material material = materialService.findMaterialById(id);
        return new Result(material);
    }

    @GetMapping("/materials")
    public Result findMaterials(Integer page, Integer limit, String name)
    {
        Map<String, Object> map = new HashMap<>();
        map.put("page", page);
        map.put("limit", limit);
        map.put("name", name);
        return materialService.findMaterialsResult(map);
    }

    @GetMapping("/materials/index")
    public Result findMaterialsIndex()
    {
        Map<String, List<String>> map = new HashMap();
        List<Material> materials = materialService.findAllMaterials();
        for (Material material : materials)
        {
            String letter = StringUtil.getPinyinFirstLetters(material.getName().substring(0, 1));
            if (!map.containsKey(letter))
            {
                map.put(letter, new ArrayList<>());
            }
            map.get(letter).add(material.getName());
        }
        List<Object> result = new ArrayList<>();
        for (Map.Entry<String, List<String>> entry : map.entrySet())
        {
            Map<String, Object> item = new HashMap<>();
            item.put("letter", entry.getKey());
            item.put("data", entry.getValue());
            result.add(item);
        }
        return new Result(result);
    }

    @DeleteMapping("/materials/{ids}")
    public Result deleteMaterialById(@PathVariable String ids)
    {
        int[] idArrays = NumberUtil.parseIntArray(ids);
        for (Integer id : idArrays)
        {
            materialService.deleteMaterialById(id);
        }
        return Result.SUCCESS;
    }

    @PutMapping("/materials")
    public Result saveMaterial(Material material)
    {
        materialService.saveMaterial(material);
        return Result.SUCCESS;
    }


    /**
     * 通过Excel批量导入司机信息
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/materials/import")
    public Result importMaterials(MultipartFile file) throws IOException
    {
        File tmp = new File(System.getProperty("java.io.tmpdir") + "/" + System.currentTimeMillis() + ".xlsx");
        file.transferTo(tmp);
        try
        {
            List<Material> materials = EasyExcel.read(tmp).head(Material.class).sheet(0).doReadSync();
            for (Material material : materials)
            {
                materialService.saveMaterial(material);
            }
            return Result.SUCCESS;
        } catch (Exception ex)
        {
            ex.printStackTrace();
            return new Result(ex.getMessage(), null);
        }
    }

    /**
     * 导出司机列表
     *
     * @throws IOException
     */
    @GetMapping("/materials/export")
    public void exportMaterials() throws IOException
    {
        String fileName = "材料清单.xlsx";
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
        List<Material> materials = materialService.findMaterials(new HashMap<>());
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        WriteSheet sheet0 = EasyExcel.writerSheet(0, "材料").head(Material.class).build();
        excelWriter.write(materials, sheet0);
        excelWriter.finish();
    }

}
